<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入名称" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="equipmentId">
              <j-dict-select-tag
                type="list"
                v-model="model.equipmentId"
                dictCode="yks_equipment,name,id"
                placeholder="请选择项目"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="运维类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="devopsPersontype">
              <j-dict-select-tag
                type="list"
                v-model="model.devopsPersontype"
                dictCode="devops_persontype"
                placeholder="请选择运维类型"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
              <a-form-model-item label="运维人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenancePerson">
                <j-dict-select-tag type="list" v-model="model.maintenancePerson" dictCode="sys_user,username,id" placeholder="请选择运维人员" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="运维部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceDept">
                <j-dict-select-tag type="list" v-model="model.maintenanceDept" dictCode="sys_depart,depart_name,id" placeholder="请选择运维部门" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="触发类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="triggerType">
                <j-dict-select-tag type="list" v-model="model.triggerType" dictCode="trigger_type" placeholder="请选择触发类型" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="初次触发时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="triggerTime">
                <j-date placeholder="请选择初次触发时间" v-model="model.triggerTime"  style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="重复次数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repeatNumber">
                <a-input v-model="model.repeatNumber" placeholder="请输入重复次数"  ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="重复间隔" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repeatGap">
                <a-input v-model="model.repeatGap" placeholder="请输入重复间隔"  ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="重复间隔单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repeatGapUnit">
                <j-dict-select-tag type="list" v-model="model.repeatGapUnit" dictCode="yks_unit,name,id" placeholder="请选择重复间隔单位" />
              </a-form-model-item>
            </a-col> -->
          <a-col :span="24">
            <a-form-model-item
              label="下次计划保养时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="maintenanceNextTime"
            >
              <j-date placeholder="请选择下次计划保养时间" v-model="model.maintenanceNextTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
              <a-form-model-item label="保养时间段开始" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceQuantumstart">
                <j-date placeholder="请选择保养时间段开始" v-model="model.maintenanceQuantumstart"  style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="保养时间段结束" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceQuantumend">
                <j-date placeholder="请选择保养时间段结束" v-model="model.maintenanceQuantumend"  style="width: 100%" />
              </a-form-model-item>
            </a-col> -->
          <!-- <a-col :span="24">
            <a-form-model-item label="保养类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceType">
              <j-dict-select-tag
                type="list"
                v-model="model.maintenanceType"
                dictCode="maintenance_type"
                placeholder="请选择保养类型"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="保养内容" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maintenanceContext">
              <a-input v-model="model.maintenanceContext" placeholder="请输入保养内容" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="保养明细" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateId">
              <j-multi-select-tag
                type="list_multi"
                v-model="model.templateId"
                dictCode="yks_maintenance_template,template_name,id"
                placeholder="请选择模版ID"
                disabled
              />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="24">
            <div v-for="item in contexts" :key="item.id" style="border: 1px solid #ccc">
              <a-form-model-item label="保养内容" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateContext">
                <div style="display: flex; margin-top: 10px">
                  <a-input v-model="item.name" placeholder="请输入保养内容" disabled></a-input>
                </div>
                <div>
                  <div v-for="detail in item.details" :key="detail.id">
                  
                    <MaintenanceTemplateControl :detail="detail" ref="maintenanceTemplateControl" forceRender></MaintenanceTemplateControl>
                  <!-- <YksMaintenanceTemplateDetailForm :detail="detail" :item="item"
                @addDetail="addDetail" @reduceDetail="reduceDetail" ref="detailForm"></YksMaintenanceTemplateDetailForm> -->
                  </div>
                </div>

                
              </a-form-model-item>
            </div>
            <a-button v-show="isShowButton&!formDisabled" @click="addMaintenanceContext" type="primary" style="margin-left: 85%;margin-top: 10px;">添加保养内容</a-button>
          </a-col>
        </a-row>
      </a-form-model>
      <yks-maintenance-template-modal ref="modalForm" @ok="modalFormOk" :isExecDevops="isExecDevops"/>
    </j-form-container>
    
  </a-spin>
</template>
  
  <script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue,randomUUID } from '@/utils/util'
import YksMaintenanceTemplateDetailForm from './YksMaintenanceTemplateDetailForm.vue'
import YksMaintenanceTemplateModal from './YksMaintenanceTemplateModal'
import moment from 'dayjs'
import MaintenanceTemplateControl from './MaintenanceTemplateControl.vue'

export default {
  name: 'YksEquipmentDevopsPlanForm',
  components: {
    YksMaintenanceTemplateDetailForm,
    YksMaintenanceTemplateModal,
    MaintenanceTemplateControl
},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
      
      formDisabled(){
        return this.disabled
      },
  },
  data() {
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        name: [{ required: true, message: '请输入名称!' }],
        equipmentId: [{ required: true, message: '请输入项目!' }],
        devopsPersontype: [{ required: true, message: '请输入运维类型!' }],
      },
      url: {
        // add: "/dev/yksEquipmentDevops/add",
        add: "/dev/yksEquipmentDevopsHistory/add",
        adddetail: "/dev/yksEquipmentDevopsHistoryDetail/add",
        edit: '/dev/yksEquipmentDevops/edit',//用于更新运维单状态
        queryById: '/dev/yksEquipmentDevops/queryById',
        yksMaintenanceTemplateDetail: {
          list: '/dev/yksMaintenanceTemplate/queryYksMaintenanceTemplateDetailByMainId',
        },
        productlist: "/dev/devEquipmentConfigProduct/list",
        materiallist: '/dev/yksEquipmentConfigurationPart/list',
        historylist: "/dev/yksEquipmentDevopsHistory/list",
      },
      contexts: [],
      selectValue:'',
      isShowButton:false,
      isExecDevops:true,
      effectiveDate:''
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    debugger
    // this.selectValue=new Map()
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    change:function(e){
      debugger
      if(this.contexts.length>0){
        for(var i=0;i<this.contexts.length;i++){
            let details=this.contexts[i].details.filter(p=>p.id==e.target.name)
            if(details.length>0)
            {
            details[0].selectValue=e.target.value
                // this.contexts[i].details.filter(p=>p.id=e.target.name)[]
            }
        }
      }
      
    },
    changeCheckBox(detail,control){
      debugger
      if(!detail.selectids){
        detail.selectids=[]
      }    
      if(!control.IsChecked){
        control.IsChecked=true
        detail.selectids.push(control.id)
      }else{
        control.IsChecked=false
        for(var i=0;i<detail.selectids.length;i++){
          if( detail.selectids[i]==control.id){
            detail.selectids.splice(i,1)
          }
        }
      }
        
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      
      this.model = Object.assign({}, record)
      if(this.model.maintenanceStatus=='2'){
        this.loadHistoryData()
      }else{
       this.isShowButton=true
        // this.loadProduct()
        // this.loadMaterial()
      
        let templateids = this.model.templateId.split(',')
        for (var i = 0; i < templateids.length; i++) {
          let params = { id: templateids[i] }
          this.loadDetailData(params)
          
        }
        this.setDefaultNextMaintenanceTime()
      }
      

      this.visible = true
    },
    setDefaultNextMaintenanceTime(){
      debugger
      if(this.model.repeatGap>0){
        let nextMaintenanceNextTime=new Date(this.model.maintenanceNextTime)
        switch(this.model.repeatGapUnit_dictText){
          case '天':
          case '日':
          nextMaintenanceNextTime.setDate(nextMaintenanceNextTime.getDate() + this.model.repeatGap)
            break
          case '周':
          case '星期':
          nextMaintenanceNextTime.setWeek(nextMaintenanceNextTime.getWeek() + this.model.repeatGap)
            break
          case '月':
          nextMaintenanceNextTime.setMonth(nextMaintenanceNextTime.getMonth() + this.model.repeatGap)
            break
          case '年':
          nextMaintenanceNextTime.setFullYear(nextMaintenanceNextTime.getFullYear() + this.model.repeatGap)
            break
        }
        this.model.maintenanceNextTime=nextMaintenanceNextTime
      }
    },
    modalFormOk(){
      let contextlist=this.$refs.modalForm.contexts
      debugger
      if(contextlist.length>0){
        for(var i=0;i<contextlist.length;i++){
            for(var j=0;j<contextlist[i].details.length;j++){
              if(contextlist[i].details[j].controlType=='6'){
                this.loadProduct(contextlist[i],contextlist[i].details[j])
              }
              if(contextlist[i].details[j].controlType=='7'){
                this.loadMaterial(contextlist[i],contextlist[i].details[j])
              }
            }
            this.contexts.push(contextlist[i])
        }
      }
    },
    addMaintenanceContext() {
      
      this.$refs.modalForm.currentEquipmentId = this.model.equipmentId
      // this.$refs.modelForm.isExecDevops=true;
        this.$refs.modalForm.add();
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
        
    },
    
    loadHistoryData(){
      let params = { id: this.model.id }
        getAction(this.url.historylist, params)
        .then((res) => {
          if (res.success) {
            debugger
            let listContexts = res.result.records || res.result;
            if(listContexts.length>0){
              let record = listContexts[0]
                this.contexts = JSON.parse(record.maintenanceItem)
                for (var i = 0; i < this.contexts.length; i++) {
                  for (var j = 0; j < this.contexts[i].details.length; j++) {
                    let detail = this.contexts[i].details[j];
                    // if (detail.controlType == '3' || detail.controlType == '4') {
                    //   for (var k = 0; k < detail.controls.length; k++) {
                    //     if (detail.selectids.indexOf(detail.controls[k].id) < 0) {
                    //       // detail.controls.splice(k,1)
                    //     }
                    //   }
                    // }
                  }
                }
                this.model = Object.assign({}, record)
            }
            
     
            
            // for (var i = 0; i < listContexts.length; i++) {
            //   let context = {}
            //   context.details=[]
            //   context.id = listContexts[i].id
            //   context.name = listContexts[i].productName


            //   let detail={controlType:'6',effectiveDate:listContexts[i].effectiveDate}//8--时间格式
            //   detail.controls=[]
            //   detail.controls.push({id:'1',value:'检查'}) 
            //   detail.controls.push({id:'2',value:'更换'})// detail={controlType:'8',name:'有效期',controlValue:listContexts[i].effectiveDate}
            //   context.details.push(detail)
            //   this.contexts.push(context)
            // }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    loadProduct(context,detail){
      debugger
      if(detail.productId){
        context.name = detail.productName
        let productIds=detail.productId.split(',')
        for(var j=0;j<productIds.length;j++){
          let params = { id: productIds[j] }
        getAction(this.url.productlist, params)
        .then((res) => {
          if (res.success) {
            let listContexts = res.result.records
            if (listContexts.length > 0) {
                    for (var i = 0; i < listContexts.length; i++) {
                      if (productIds[0] == listContexts[i].id) {
                        detail.name = listContexts[i].productName + "有效期"
                        detail.effectiveDate = listContexts[i].effectiveDate
                        detail.productId = listContexts[i].id
                        detail.controls = []
                        detail.controls.push({ id: '1', value: '检查', label: '检查' })
                        detail.controls.push({ id: '2', value: '更换', label: '更换' })// detail={controlType:'8',name:'有效期',controlValue:listContexts[i].effectiveDate}
                      }
                      else {
                        let newDetail = Object.assign({}, detail)
                        newDetail.id=randomUUID()
                        newDetail.name = listContexts[i].productName + "有效期"
                        newDetail.effectiveDate = listContexts[i].effectiveDate
                        newDetail.productId = listContexts[i].id
                        newDetail.controls = []
                        newDetail.controls.push({ id: '1', value: '检查', label: '检查' })
                        newDetail.controls.push({ id: '2', value: '更换', label: '更换' })// detail={controlType:'8',name:'有效期',controlValue:listContexts[i].effectiveDate}
                        context.details.push(newDetail)
                      }

                    }

                    this.refreshContext()
                  }
            
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })

        }
      }
      
      
    },
    loadMaterial(context,detail){
      
      if(detail.materialId){
        context.name = detail.materialName
        let materialIds=detail.materialId.split(',')
        for(var j=0;j<materialIds.length;j++){
        let params = { id: materialIds[j] }
        getAction(this.url.materiallist, params)
        .then((res) => {
          debugger
          if (res.success) {
            let listContexts = res.result.records
            if (listContexts.length > 0) {
                    for (var i = 0; i < listContexts.length; i++) {
                      if (materialIds[0] == listContexts[i].id) {
                        detail.name = listContexts[i].materialName + "有效期"
                        detail.effectiveDate = listContexts[i].effectiveDate
                        detail.materialId = listContexts[i].id
                        detail.controls = []
                        detail.controls.push({ id: '1', value: '检查', label: '检查' })
                        detail.controls.push({ id: '2', value: '更换', label: '更换' })
                        detail.controls.push({ id: '3', value: '维修', label: '维修' })
                      }
                      else {
                        let newDetail = Object.assign({}, detail)
                        newDetail.id = randomUUID()
                        detail.name = listContexts[i].materialName + "有效期"
                        detail.effectiveDate = listContexts[i].effectiveDate
                        detail.materialId = listContexts[i].id
                        detail.controls = []
                        detail.controls.push({ id: '1', value: '检查', label: '检查' })
                        detail.controls.push({ id: '2', value: '更换', label: '更换' })
                        detail.controls.push({ id: '3', value: '维修', label: '维修' })
                        context.details.push(newDetail)
                      }

                    }

                    this.refreshContext()
                  }
           

          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
        }
    }
    },
    submitForm() {
      this.saveDevopsHistory()
      //更新保养单信息
      this.updateDevops()
    },
    saveDevopsHistory(){
      const that = this
      let valid=true
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
        //   if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
        //   } else {
        //     httpurl += this.url.edit
        //     method = 'put'
        //   }
         this.model.devopsId=this.model.id
         this.model.maintenancePlanTime=this.model.maintenanceNextTime
         var myDate = new Date();
         this.model.maintenanceActualTime=myDate.getFullYear()+'-'+myDate.getMonth()+'-'+myDate.getDate()+' '+myDate.toLocaleTimeString()
          this.model.maintenanceItem=JSON.stringify(this.contexts)
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
            if (this.contexts.length > 0) {
              for (var i = 0; i < this.contexts.length; i++) {
                let details=this.contexts[i].details.filter(p=>p.controlType=='6'||p.controlType=='7')
                if (details.length > 0) {
                  for(var j=0;j<details.length;j++){
                    let detail={}
                    detail.name=details[j].controlValue
                    detail.context=details[j].maintenanceType
                    debugger
                    detail.equipmentId=that.model.equipmentId
                    if(details[j].controlType=='6'){
                      detail.productId=details[j].productId
                    }
                    if(details[j].controlType=='7'){
                      detail.materialId=details[j].materialId
                    }
                    
                    detail.effectiveDate=details[j].effectiveDate
                    detail.devopsId=that.model.id
                    //保存化学药剂和材料明细
                  httpAction(this.url.adddetail, detail, method)
                    .then((res) => {
                      if (res.success) {
                        // that.$message.success(res.message)
                        that.$emit('ok')
                      } else {
                        that.$message.warning(res.message)
                      }
                    })
                    .finally(() => {
                      that.confirmLoading = false
                    })

                  }
                  
                }
                
              }
            }
            
           
        }
      }
      )
    },
    updateDevops(){

      let that=this
      let valid=true
      if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
            httpurl += this.url.edit
            method = 'put'
          this.model.maintenanceStatus='2'  //已处理
          
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
    }, 
    loadDetailData(params) {
      getAction(this.url.yksMaintenanceTemplateDetail.list, params)
        .then((res) => {
          
          if (res.success) {
            let listContexts = res.result.filter((p) => p.extText == 'context')
            for (var i = 0; i < listContexts.length; i++) {
              let context = {}
              context.id = listContexts[i].id
              context.name = listContexts[i].name
              context.extText = listContexts[i].extText
              context.extText1 = listContexts[i].extText1
              this.contexts.push(context)
            }
            debugger
            for (var i = 0; i < this.contexts.length; i++) {
              this.contexts[i].details = res.result.filter(
                (p) => p.extText == 'control' && p.extText1 == this.contexts[i].extText1
              )
              for (var j = 0; j < this.contexts[i].details.length; j++) {
                let detail = this.contexts[i].details[j]
                if (detail.controlType == '3' || detail.controlType == '4') {
                  let controls = JSON.parse(detail.controlValue)
                  detail.controlValue = ''
                  for(var k=0;k<controls.length;k++){
                    
                    //  detail.contorls[k].IsChecked=false
                    controls[k].label=controls[k].value
                    controls[k].value=controls[k].id
                  }
                  detail.controls=controls
                //   detail.contorls.foreach(p=>p.IsChecked=false)

                }else if(detail.controlType=='6'){
                  detail.productId=detail.extText2
                  this.loadProduct(this.contexts[i],detail)
                }else if(detail.controlType=='7'){
                  detail.materialId=detail.extText2
                  this.loadMaterial(this.contexts[i],detail)
                }
              }
            }
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            // this.dataSource = res.result.records||res.result;
            // if(res.result.total)
            // {
            //   this.ipagination.total = res.result.total;
            // }else{
            //   this.ipagination.total = 0;
            // }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    refreshContext(){
      if(this.$refs.maintenanceTemplateControl.length>0){
        for(var i=0;i<this.$refs.maintenanceTemplateControl.length;i++){
          this.$refs.maintenanceTemplateControl[i].refresh() // 调用子组件的方法进行刷新
        }
      }
      // debugger
      // let contextlist=this.contexts;
      // if(contextlist.length>0){
      //   this.contexts=[]
      //   for(var i=0;i<contextlist.length;i++){
      //     this.contexts.push(contextlist[i])
      //   }
       
      // }
    },
    saveDevops(){
        let that=this
        let valid=true
        if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.model.maintenanceItem=JSON.stringify(this.contexts)
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
    },
    // formDevopsData(){
    //     let devopsItems
    //     for(var i=0;i<this.contexts.length;i++){

    //     }
    // }
  },
}
</script>